<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\DailyQuestion as DailyQuestionModel;
use app\admin\model\UserPoints;
use think\Db;
use think\Request;
use think\Validate;

/**
 * 每日一题API接口
 */
class DailyQuestion extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = '*';
    // 无需鉴权的接口  
    protected $noNeedRight = '*';

    /**
     * 获取随机题目
     */
    public function getRandomQuestion()
    {
        try {
            $question = Db::name('daily_question')
                ->where('status', 1)
                ->orderRaw('RAND()')
                ->find();
            
            if (!$question) {
                return json(['code' => 404, 'msg' => '暂无题目数据', 'data' => null]);
            }
            
            // 将选项转换为JSON格式
            $options = [
                ['key' => 'A', 'text' => $question['option_a']],
                ['key' => 'B', 'text' => $question['option_b']],
                ['key' => 'C', 'text' => $question['option_c']],
                ['key' => 'D', 'text' => $question['option_d']]
            ];
            
            // 格式化返回数据
            $result = [
                'id' => $question['id'],
                'question' => $question['question'],
                'options' => json_encode($options),
                'correct_answer' => $question['correct_answer'],
                'explanation' => $question['explanation'],
                'difficulty' => $question['difficulty'],
                'points' => $question['points'],
                'category' => $question['category'] ?? '',
                'tags' => $question['tags'] ?? ''
            ];
            
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $result]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取题目失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取题目列表
     */
    public function getQuestionList()
    {
        try {
            $page = input('page', 1);
            $limit = input('limit', 10);
            $category = input('category', '');
            $difficulty = input('difficulty', '');
            
            $where = [
                ['status', '=', 1]
            ];
            
            if (!empty($category)) {
                $where[] = ['category', '=', $category];
            }
            
            if (!empty($difficulty)) {
                $where[] = ['difficulty', '=', $difficulty];
            }
            
            $questions = Db::name('daily_question')
                ->where($where)
                ->order('weigh desc, id desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            // 格式化数据
            $list = [];
            foreach ($questions->items() as $question) {
                // 将选项转换为JSON格式
                $options = [
                    ['key' => 'A', 'text' => $question['option_a']],
                    ['key' => 'B', 'text' => $question['option_b']],
                    ['key' => 'C', 'text' => $question['option_c']],
                    ['key' => 'D', 'text' => $question['option_d']]
                ];
                
                $list[] = [
                    'id' => $question['id'],
                    'question' => $question['question'],
                    'options' => json_encode($options),
                    'correct_answer' => $question['correct_answer'],
                    'explanation' => $question['explanation'],
                    'difficulty' => $question['difficulty'],
                    'points' => $question['points'],
                    'category' => $question['category'] ?? '',
                    'tags' => $question['tags'] ?? '',
                    'create_time' => $question['create_time']
                ];
            }
            
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $list,
                'total' => $questions->total(),
                'page' => $page,
                'limit' => $limit
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取题目列表失败：' . $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * 根据ID获取指定题目
     * @param int $id 题目ID
     * @return \think\response\Json
     */
    public function getQuestionById($id = null)
    {
        if (!$id) {
            return json([
                'code' => 0,
                'msg' => '题目ID不能为空',
                'data' => null
            ]);
        }

        try {
            $question = Db::name('daily_question')
                ->where('id', $id)
                ->where('status', 1)
                ->where('delete_time', null)
                ->find();

            if (!$question) {
                return json([
                    'code' => 0,
                    'msg' => '题目不存在',
                    'data' => null
                ]);
            }

            // 格式化选项数据
            $options = [
                ['key' => 'A', 'text' => $question['option_a']],
                ['key' => 'B', 'text' => $question['option_b']],
                ['key' => 'C', 'text' => $question['option_c']],
                ['key' => 'D', 'text' => $question['option_d']]
            ];

            $result = [
                'id' => $question['id'],
                'question' => $question['question'],
                'options' => $options,
                'correctAnswer' => $question['correct_answer'],
                'explanation' => $question['explanation'],
                'difficulty' => $question['difficulty'],
                'points' => $question['points'],
                'category' => $question['category'],
                'tags' => $question['tags']
            ];

            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取题目失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 根据分类获取题目
     * @param string $category 分类名称
     * @return \think\response\Json
     */
    public function getQuestionsByCategory($category = '')
    {
        if (!$category) {
            return json([
                'code' => 0,
                'msg' => '分类不能为空',
                'data' => null
            ]);
        }

        try {
            $questions = Db::name('daily_question')
                ->where('category', $category)
                ->where('status', 1)
                ->where('delete_time', null)
                ->order('weigh desc, id desc')
                ->select();

            $result = [];
            foreach ($questions as $question) {
                $options = [
                    ['key' => 'A', 'text' => $question['option_a']],
                    ['key' => 'B', 'text' => $question['option_b']],
                    ['key' => 'C', 'text' => $question['option_c']],
                    ['key' => 'D', 'text' => $question['option_d']]
                ];

                $result[] = [
                    'id' => $question['id'],
                    'question' => $question['question'],
                    'options' => $options,
                    'correctAnswer' => $question['correct_answer'],
                    'explanation' => $question['explanation'],
                    'difficulty' => $question['difficulty'],
                    'points' => $question['points'],
                    'category' => $question['category'],
                    'tags' => $question['tags']
                ];
            }

            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $result,
                'count' => count($result)
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取题目失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 提交答题结果
     */
    public function submitAnswer()
    {
        $user = $this->auth->getUser(true);
        $userId = $user ? $user['uid'] : 1; // 测试时使用默认用户ID 1

        $data = input('post.');
        
        // 验证数据
        $validate = new Validate();
        $validate->rule([
            'question_id' => 'require|integer',
            'user_answer' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        try {
            // 首先检查今日是否已经答过题
            $hasAnswered = UserPoints::checkTodayPoints($userId, 'daily_question');
            if ($hasAnswered) {
                return json([
                    'code' => 403, 
                    'msg' => '您今日已经答过题了，明天再来吧！',
                    'data' => [
                        'has_answered_today' => true,
                        'can_answer' => false
                    ]
                ]);
            }

            // 获取题目信息
            $question = Db::name('daily_question')
                ->where('id', $data['question_id'])
                ->where('status', 1)
                ->find();

            if (!$question) {
                return json(['code' => 404, 'msg' => '题目不存在']);
            }

            // 判断答案是否正确
            $isCorrect = strtoupper($data['user_answer']) === strtoupper($question['correct_answer']);
            
            $result = [
                'is_correct' => $isCorrect,
                'correct_answer' => $question['correct_answer'],
                'explanation' => $question['explanation'],
                'points_awarded' => 0,
                'has_answered_today' => false,
                'can_answer_again' => false
            ];

            // 如果答案正确，给予积分奖励
            if ($isCorrect) {
                // 添加积分奖励
                $pointsResult = UserPoints::addPoints(
                    $userId,
                    3,
                    'daily_question',
                    $data['question_id'],
                    '每日答题正确奖励'
                );
                
                if ($pointsResult) {
                    $result['points_awarded'] = 3;
                    $result['has_answered_today'] = true;
                    $result['message'] = '恭喜您答对了！已为您加了3个积分！今日答题已完成，明天再来挑战吧！';
                } else {
                    $result['message'] = '答案正确！但积分奖励失败，请联系管理员。';
                }
            } else {
                // 答错了不记录积分，允许继续答题
                $result['has_answered_today'] = false;
                $result['can_answer_again'] = true;
                $result['message'] = '答案错误！正确答案是：' . $question['correct_answer'] . '。您可以换一题继续挑战！';
            }

            // 获取用户当前积分汇总
            $pointsSummary = UserPoints::getUserPointsSummary($userId);
            $result['total_points'] = $pointsSummary['total_points'];
            $result['today_points'] = $pointsSummary['today_points'];

            return json([
                'code' => 200,
                'data' => $result,
                'msg' => $result['message']
            ]);

        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '提交答案失败：' . $e->getMessage()]);
        }
    }

    /**
     * 检查今日答题状态
     */
    public function checkTodayStatus()
    {
        $user = $this->auth->getUser(true);
        $userId = $user ? $user['uid'] : 1; // 测试时使用默认用户ID 1

        try {
            $hasAnswered = UserPoints::checkTodayPoints($userId, 'daily_question');
            $summary = UserPoints::getUserPointsSummary($userId);
            
            return json([
                'code' => 200,
                'data' => [
                    'has_answered_today' => $hasAnswered,
                    'today_points' => $summary['today_points'],
                    'total_points' => $summary['total_points'],
                    'available_points' => $summary['available_points']
                ],
                'msg' => '获取成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取状态失败：' . $e->getMessage()]);
        }
    }
}